package com.imooc.project.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.MD5;
import com.imooc.project.entity.Account;
import com.imooc.project.service.AccountService;
import com.imooc.project.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    AccountService accountService;

    @GetMapping("add")
    public String register(){

        return "login/register";
    }
    @PostMapping

    public String add(Account account) {
        setPasswordAndSalt(account);
        if(accountService.save(account)){

            return "redirect:/";
        }
       return "login/register";
    }

    //封装
    private void setPasswordAndSalt(Account account) {
        String password = account.getPassword();
        String salt = UUID.fastUUID().toString().replaceAll("-", "");
        MD5 md5 = new MD5(salt.getBytes());

        String digestHex = md5.digestHex(password);  // 加密后的密文密码
        account.setPassword(digestHex);
        account.setSalt(salt);
    }
}
